package com.maycari.captainbi.scheduled;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.maycari.captainbi.common.exception.BusinessException;
import com.maycari.captainbi.data.dto.*;
import com.maycari.captainbi.service.Captain12Service;
import com.maycari.captainbi.service.Captain13Service;
import com.maycari.captainbi.service.Captain14Service;
import com.maycari.captainbi.util.CaptainBIUtil;
import com.maycari.captainbi.util.MaycariRedis;
import com.maycari.tool.utils.DateUtil;
import com.maycari.tool.utils.ThreadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TreeMap;

@Component
public class Task13_14 implements ApplicationRunner {

    @Autowired
    private MaycariRedis maycariRedis;

    private static String start_time_str = "2021-03-01 00:00:00";

    private static String dataKey = "MAYCARI:DATAKEY13_14";

    private static String action = "http://cronapi.captainbi.com/index.php?m=cronapi&c=goods&a=getAmazonGoodsFinanceShareList";

    private static String dataKey2 = "MAYCARI:DATAKEY13_14";

    private static String action2 = "http://cronapi.captainbi.com/index.php?m=cronapi&c=goods&a=getAmazonGoodsFinanceShareItemsList";

    @Autowired
    private Captain13Service captain13Service;
    @Autowired
    private Captain14Service captain14Service;

    /*@Scheduled(cron = "0 0 1 * * ?")*/
    public void task() {
        System.out.println(1);

    }

    private void getData() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        int page = 1;
        int page_size = 100;

        Date start_time = maycariRedis.get(dataKey);
        System.err.println(start_time);
        if (start_time == null) {
            start_time = DateUtil.parse(start_time_str, DateUtil.PATTERN_DATETIME);
        }

        Date now = new Date();

        JSONArray jsonArray = new JSONArray();

        while (true) {
            //一天
            Date end_time = DateUtil.minusSeconds(DateUtil.plusDays(start_time, 1), 1);

            if (end_time.after(now)) {
                break;
            }
            while (true) {
                ThreadUtil.sleep(1000);
                TreeMap<String, String> params = new TreeMap<>();
                params.put("page", String.valueOf(page));
                params.put("page_size", String.valueOf(page_size));
                params.put("start_time", simpleDateFormat.format(start_time));
                params.put("end_time", simpleDateFormat.format(end_time));
                String result = CaptainBIUtil.sendRequest(action, params);
                JSONObject jsonObject = JSON.parseObject(result, Feature.OrderedField);
                int code = jsonObject.getIntValue("code");
                if (code == 200) {
                    JSONArray data = jsonObject.getJSONArray("data");
                    if (data != null && data.size() > 0) {
                        if (data.size() >= 100) {
                            //可能还有数据  继续请求
                            jsonArray.addAll(data);
                            page++;
                        } else {
                            jsonArray.addAll(data);
                            break;
                        }
                    } else {
                        break;
                    }
                } else {
                    throw new BusinessException(String.format("Task1 error :【%s】", jsonObject.getString("msg")));
                }
            }
            start_time = DateUtil.plusSeconds(end_time, 1);
        }
        List<Captain13Dto> captain13Dtos = jsonArray.toJavaList(Captain13Dto.class);
        List<Captain14Dto> captain14Dtos = getRecord(captain13Dtos);

        captain13Service.insertBatch(captain13Dtos,captain14Dtos);
//        captain13Service.insertBatch(captain13Dtos);
        maycariRedis.set(dataKey, start_time);
//        getRecord(jsonArray);
    }


    private List<Captain14Dto> getRecord(List<Captain13Dto> captain13Dtos){
        TreeMap<String, String> params = new TreeMap<>();
        int page = 1;
        int page_size = 100;
        List<Captain14Dto> list = new ArrayList<>();
        for (Captain13Dto captain13Dto : captain13Dtos) {

            while (true) {
                ThreadUtil.sleep(1000);
                params.clear();
                params.put("page", String.valueOf(page));
                params.put("page_size", String.valueOf(page_size));
                params.put("share_id", String.valueOf(captain13Dto.getId()));
                String result = CaptainBIUtil.sendRequest(action2, params);
                JSONObject jsonObject = JSON.parseObject(result, Feature.OrderedField);
                int code = jsonObject.getIntValue("code");
                if (code == 200) {
                    JSONArray data = jsonObject.getJSONArray("data");
                    if (data != null && data.size() > 0) {
                        if (data.size() >= 100) {
                            //可能还有数据  继续请求
                            list.addAll(data.toJavaList(Captain14Dto.class));
                            page++;
                        } else {
                            list.addAll(data.toJavaList(Captain14Dto.class));
                            break;
                        }
                    } else {
                        break;
                    }
                } else {
                    throw new BusinessException(String.format("Task13_14 error :【%s】", jsonObject.getString("msg")));
                }
            }


        }
        return list;
    }

    private void getRecord(JSONArray jsonArray) {
        JSONArray jsonArray1 = new JSONArray();

        int page = 1;
        int page_size = 100;

        for (Object object : jsonArray) {
            ThreadUtil.sleep(1000);
            if (object instanceof JSONObject) {
                JSONObject object1 = (JSONObject) object;
                String id = object1.getString("id");

                TreeMap<String, String> params = new TreeMap<>();
                params.put("page", String.valueOf(page));
                params.put("page_size", String.valueOf(page_size));
                params.put("share_id", id);

                String result = CaptainBIUtil.sendRequest(action2, params);

                JSONObject jsonObject = JSON.parseObject(result, Feature.OrderedField);
                int code = jsonObject.getIntValue("code");
                if (code == 200) {
                    JSONArray data = jsonObject.getJSONArray("data");
                    if (data != null && data.size() > 0) {
                        jsonArray1.addAll(data);
                    }
                }
            }
        }
        List<Captain14Dto> collect = jsonArray1.toJavaList(Captain14Dto.class);
//        captain14Service.insertBatch(collect);
        maycariRedis.set(dataKey2, new Date());
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        //getData();
    }
}
